#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import tornado
import tornado.web
from config import etc
from utils import log, util, session_mc, session_base
from utils.session_mc import McBaseStore

cms_user_store = McBaseStore(McBaseStore.PREFIXES[1])
scms_session_name = "scms_sessionid"

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        session_id = self.get_secure_cookie(scms_session_name)

        return cms_user_store.get(session_id)


def admin_required(request):
    @tornado.web.asynchronous
    def Process(handler, *args):
        # 请求前检验Session数据的过程
        if not handler.current_user:
            log.w('admin_required')
            if handler.request.method == "GET":
                handler.redirect("/cms2/signin")
                return

            res = {'idx': -1, 'ret': -3, 'msg': etc.err_signin_requied, 'res': {}}
            handler.write(json.dumps(res))
            handler.finish()
            return
        # 执行原本请求的方法
        try:
            request(handler, *args)
        except Exception as e:
            log.exp(e)
            res = {'idx': -1, 'ret': -4, 'msg': etc.err_500, 'res': {}}
            handler.write(json.dumps(res))
            handler.finish()
            return

    return Process


def cms_login(handler, user_base, expires):
    session_id = session_base.generate_id()
    cms_user_store.set(session_id, user_base['username'])

    domain = util.get_domain_from_host(handler.request.host)
    handler.set_secure_cookie(scms_session_name, session_id, domain=domain, expires=expires)